﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;

namespace UDS.Build.Database
{
    public abstract class DatabaseBuildTaskBase : Task
    {
        private const string singleQuoteError = "Parameter cannot contain single quotes";
        // Check for SQL injection
        // all params must not have single quotes in them
        protected void CheckSingleQuotes(string paramName, string param)
        {
            if (param.IndexOf('\'') != -1)
            {
                throw new ArgumentException(singleQuoteError, paramName);
            }
        }

        protected SqlConnection MakeConnection()
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.DataSource = SqlServerInstance;
            builder.InitialCatalog = DatabaseName;
            builder.IntegratedSecurity = true;
            builder.MultipleActiveResultSets = true;
            builder.ApplicationName = this.GetType().Name;
            SqlConnection conn = new SqlConnection(builder.ConnectionString);
            conn.Open();

            return conn;
        }

        #region BuildTask params
        private string databaseName;
        [Required]
        public string DatabaseName
        {
            get
            {
                return databaseName;
            }
            set
            {
                CheckSingleQuotes("DatabaseName", value);
                databaseName = value;
            }
        }

        [Required]
        public string SqlServerInstance
        {
            get;
            set;
        }
        #endregion
    }
}
